package com.qk.management.web.filter;


import cn.hutool.core.util.ObjectUtil;
import com.qk.common.util.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;

import java.io.IOException;

/**
 * @Author:gzc
 * @Date: 2025/10/11 9:49
 * @Description:
 */
@Slf4j
//@WebFilter("/*")
public class TokenFilter implements Filter {

    private static final String LOGIN_PATH = "/login";
    private static final String TOKEN_HEADER_NAME = "token";
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        if (ObjectUtil.equals(request.getServletPath(), LOGIN_PATH)){
            log.info("登录操作, 直接放行");
            filterChain.doFilter(request, response);
            return;
        }

        String token = request.getHeader(TOKEN_HEADER_NAME);
        if (ObjectUtil.isEmpty(token)) {
            log.info("token为空, 登录失败");
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
            return;
        }

        try {
            log.info("filter开始解析token");
            Claims claims = JwtUtils.parseToken(token);
            Integer id = claims.get("id", Integer.class);
            String username = claims.get("username", String.class);
        } catch (Exception e) {
            log.info("解析 token 出错, 拒绝访问, 401");
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
            return;
        }
        log.info("token 解析成功, 放行");
        filterChain.doFilter(request, response);
    }
}
